package com.media.bean.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Servlet 注解配置信息
 */
@WebServlet(name = "/Login")
public class LoginServlet extends HttpServlet {

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        if ("1".equals(request.getParameter("invalidate")) && session.getAttribute("username") != null) {
            session.invalidate();
            response.sendRedirect("login.jsp");
        }
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "select * from user where username = ? and password = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, usermame);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            if (rs.next()) {
                session.setAttribute("username", username);
                response.setHeader("refresh", "url=login.jsp");
            } else {
                out.print("登陆失败");
                response.setHeader("refresh", "3;url=login.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}